package message

import (
	"gitee.com/zjlsliupei/ghelp"
	"gitee.com/zjlsliupei/ndb/config"
	"gitee.com/zjlsliupei/ndb/request"
	"github.com/gin-gonic/gin"
	"github.com/tidwall/gjson"
)

type List struct {
	option     config.Option
	rpcName    string
	funcName   string
	arg        ghelp.MAP
	meta       ghelp.MAP
	ginContext *gin.Context
}

func NewList(option config.Option, rpcName string) List {
	return List{
		option:   option,
		rpcName:  rpcName,
		funcName: "List",
		arg:      make(ghelp.MAP),
	}
}

// SetGroupId 不超过20位，用于数据分组
func (this *List) SetGroupId(groupId string) *List {
	this.arg["group_id"] = groupId
	return this
}

// SetSearchText 搜索内容
func (this *List) SetSearchText(searchText string) *List {
	this.arg["searchtext"] = searchText
	return this
}

// SetFilter 用于消息的筛选，数组格式，每个数组之间是and关系，每个数组里面的条件是or关系，必填
func (this *List) SetFilter(filter []interface{}) *List {
	this.arg["filter"] = filter
	return this
}

// SetLastId 上一次List返回的lastid，配合order,默认是返回小于lastid的消息，如果order是asc，则返回大于lastid的消息
func (this *List) SetLastId(lastId string) *List {
	this.arg["lastid"] = lastId
	return this
}

// SetSize 返回条数，不能超过1000，默认15
func (this *List) SetSize(size int64) *List {
	this.arg["size"] = size
	return this
}

// SetOrder 排序，默认desc，正序是asc
func (this *List) SetOrder(order string) *List {
	this.arg["order"] = order
	return this
}

// AutoMeta 自动设置meta，根据gin的上下文来解析，meta; 如果同时使用了Meta优先以Meta为准
func (this *List) AutoMeta(c *gin.Context) *List {
	_c := c.Copy()
	this.ginContext = _c
	return this
}

// SetMeta 设置meta
func (this *List) SetMeta(meta ghelp.MAP) *List {
	this.meta = meta
	return this
}

func (this *List) Do() (gjson.Result, error) {
	req := request.NewRequest(this.option.Addr)
	req.FuncName(this.funcName)
	req.RpcName(this.rpcName)
	req.AutoMeta(this.ginContext)
	req.SetMeta(this.meta)
	return req.Do(this.arg)
}
